<template lang="pug">
.edit
  .edit-warp
    .edit-container
      .edit-header
        el-button(icon="el-icon-arrow-left" size="small" name="back" @click="$router.back()") 返回
        .edit-header-title 添加案例
      .edit-section
        .edit-section-title 基本信息
        .edit-section-body
          .form-item
            .form-item-label.important 名称案例：
            .form-item-bd
              el-input(placeholder="请输入案例名称" size="small" v-model="form.projectName")
          .form-item
            .form-item-label.important 所属业态：
            .form-item-bd
              el-select(placeholder="请选择所属业态" multiple size="small" v-model="activeStyles")
                el-option(v-for="item in styles", :label="item.styleName", :value="item.styleId")
          .form-item.form-item-start
            .form-item-label.important 项目地址：
            .form-item-bd
              .form-item-address
                el-select(v-model="countries" size="small")
                  el-option(label="中国", value="1") 中国
                el-select(v-model="form.province" size="small" @change="changeProvince")
                  el-option(v-for="item in provinces", :label="item.name", :value="item.id") {{item.name}}
                el-select(v-model="form.city" size="small")
                  el-option(v-for="item in citys", :label="item.name", :value="item.id") {{item.name}}
              .form-item-address-detail
                el-input(placeholder="请填写详细地址" v-model="form.detailAddress" size="small")
          .form-item
            .form-item-label.important 项目时间：
            .form-item-bd
              el-date-picker(placeholder="请选择项目时间" v-model="form.caseDate" value-format="yyyy-MM-dd" size="small")
      .edit-section
        .edit-section-title 案例信息
        .edit-section-body
          .form-item
            .form-item-label.important 选择类型：
            .form-item-bd
              el-radio-group(v-model="form.type" @change="changeType")
                el-radio(:label="0") 图片
                el-radio(:label="1") 视频
          .form-item.form-item-start(v-if="form.type == 0")
            .form-item-label.important 案例图片：
            .form-item-bd
              el-upload(
                action="#"
                class="upload-demo"
                :limit="limit"
                :multiple="true"
                accept="image/png, image/jpeg, image/jpg"
                ref="uploadGrid"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleGridChange"
                :on-exceed="handleGridExceed"
              )
                el-button(size="small" name="primary" slot="trigger") 上传图片
              .form-item-upload-info 文件大小≤5M，建议尺寸800*800px，可以选择图片关联相关的材料，最多5张
              .upload-photo(v-for="item, itemIndex in form.banner")
                .upload-img
                  .iconfont.el-icon-error(@click="delBanner(itemIndex)")
                  .upload-img-bd(:style="item.picUrl | filterUrl")
                  .upload-img-add(@click="addMaterial(item)") 添加材料
                .upload-materials(v-if="item.materialsList.length")
                  .upload-tr-item(v-for="row, rowIndex in item.materialsList")
                    .upload-tr(v-if="rowIndex < item.moreNum")
                      .upload-td.upload-td-bd {{row.materialName}}
                      .upload-td.upload-handle(@click="delMaterial(item, row, rowIndex)") 删除
                  .upload-more(v-if="item.materialsList.length > 3" @click="toggleMore(item)")
                    .upload-more-txt {{item.moreNum == 3 ? '查看更多' : '收起'}}
                    .iconfont.el-icon-arrow-down
          .form-item.form-item-start(v-if="form.type == 1")
            .form-item-label.important 案例视频：
            .form-item-bd
              el-upload(
                action="#"
                class="upload-demo"
                :limit="limit"
                :multiple="true"
                accept="video/*"
                ref="uploadGrid"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleGridChange"
                :on-exceed="handleGridExceed"
              )
                el-button(size="small" name="primary" slot="trigger") 添加视频
              //- .form-item-upload-info 文件大小≤5M，建议尺寸800*800px，可以选择图片关联相关的材料，最多5张
              .upload-photo(v-for="item, itemIndex in form.banner")
                .upload-img
                  .iconfont.el-icon-error(@click="delBanner(itemIndex)")
                  video.upload-img-bd(:src="item.picUrl | filterSrc")
                  .upload-img-add(@click="addMaterial(item)") 添加材料
                .upload-materials(v-if="item.materialsList.length")
                  .upload-tr-item(v-for="row, rowIndex in item.materialsList")
                    .upload-tr(v-if="rowIndex < item.moreNum")
                      .upload-td.upload-td-bd {{row.materialName}}
                      .upload-td.upload-handle(@click="delMaterial(item, row, rowIndex)") 删除
                  .upload-more(v-if="item.materialsList.length > 3" @click="toggleMore(item)")
                    .upload-more-txt {{item.moreNum == 3 ? '查看更多' : '收起'}}
                    .iconfont.el-icon-arrow-down
          .form-item.form-item-start
            .form-item-label.important 案例详情：
            .form-item-bd
              el-input(type="textarea" placeholder="请输入案例介绍" v-model="form.projectDetail" rows="3")
          .form-item
            .form-item-label.important 风格：
            .form-item-bd
              el-checkbox-group(v-model="form.styleLabelIdList")
                el-checkbox(v-for="item in styleLabel" :label="item.id") {{item.labelName}}
          .form-item
            .form-item-label.important 类型：
            .form-item-bd
              el-checkbox-group(v-model="form.typeLabelIdList")
                el-checkbox(v-for="item in typeLabel" :label="item.id") {{item.labelName}}
  //- .edit-hidden-upload(v-show="false")
  //-   el-upload(
  //-     action="#"
  //-     class="upload-demo"
  //-     :limit="limit"
  //-     :multiple="true"
  //-     accept="image/png, image/jpeg, image/jpg"
  //-     ref="hiddenUpload"
  //-     :show-file-list="false"
  //-     :auto-upload="false"
  //-     :on-change="handleQuillChange"
  //-   )
  //-     el-button(size="small" name="primary" slot="trigger") 上传图片
  .edit-footer
    el-button(size="small") 取消
    el-button(type="primary" size="small" @click="save") 保存
  select-material-modal(:show="showMaterialModal", :selectIds="selectIds", :item="currentItem" @confirm="confirmModal" @close="closeModal")
</template>

<script>
import { getAddres, getStyles, FileUpload, saveFileManage, addOrUpdate, getCaseDetail, getLabelList } from 'api'
import selectMaterialModal from '@/components/modal/selectMaterialModal'
import Quill from 'quill'
export default {
  name: 'caseEdit',
  data () {
    return {
      editorOption: {
        placeholder: '请输入自定义内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ script: 'sub' }, { script: 'super' }],
            [{ indent: '-1' }, { indent: '+1' }],
            [{ direction: 'rtl' }],
            [{ size: ['small', false, 'large', 'huge' ] }],
            [{ header: [1, 2, 3, 4, false] }],
            [{ color: [] }, { background: [] }],
            [{ font: [] }],
            [{ align: [] }],
            ['image'],
            ['clear']
          ]
        }
      },
      form: {
        styleLabelIdList: [],
        typeLabelIdList: [],
        type: 0,
        projectName: '',
        styleId: [],
        province: '',
        city: '',
        detailAddress: '',
        caseDate: '',
        projectDetail: '',
        banner: []
      },
      activeStyles: [],
      countries: '1',
      provinces: [],
      citys: [],
      styles: [],
      showMaterialModal: false,
      currentItem: {},
      selectIds: [],
      styleLabel: [],
      typeLabel: []
    }
  },
  components: {
    selectMaterialModal
  },
  computed: {
    limit: {
      get () {
        return 5 - this.form.banner.length ? 5 - this.form.banner.length : -1
      }
    },
  },
  methods: {
    changeType (value) {
      this.form.banner = []
    },
    async getList () {
      try {
        const { ResultSet } = await this.$axios.post(getLabelList)
        this.styleLabel = ResultSet.userData.data.styleLabel || []
        this.typeLabel = ResultSet.userData.data.typeLabel || []
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    toggleMore (item) {
      if (parseInt(item.moreNum) === 3) {
        item.moreNum = 9999999999999999
      } else {
        item.moreNum = 3
      }
    },
    async getAddress ({ type, id = 0 }) {
      try {
        const { ResultSet } = await this.$axios.post(getAddres, { content: { id } })
        this[type] = ResultSet.userData.getAddreList
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getStyles () {
      try {
        const { ResultSet } = await this.$axios.post(getStyles)
        this.styles = ResultSet.userData.businessStyles
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async handleGridChange (file, fileList) {
      try {
        let fileObj = await this.fileUpload(file.raw)
        this.form.banner.push({ picUrl: fileObj.fileUrl, picId: fileObj.fileId, materialsList: [] })
        this.$refs.uploadGrid.clearFiles()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    delBanner (index) {
      this.form.banner.splice(index, 1)
    },
    async fileUpload (raw) {
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    changeProvince (value) {
      this.form.city = ''
      this.getAddress({ type: 'citys', id: value })
    },
    // 点击图片ICON触发事件
    // imgHandler(state) {
    //   this.addRange = this.$refs.myQuillEditor.quill.getSelection()
    //   if (state) {
    //     this.$refs.hiddenUpload.$children[0].$refs.input.click()
    //   }
    //   this.uploadType = 'image'
    // },
    // async handleQuillChange (file, fileList) {
    //   try {
    //     let host = window.location.hostname === '123.58.39.242' ? 'https://erp.jaid.cn/' : 'http://113.106.91.68:1292'
    //     let fileObj = await this.fileUpload(file.raw)
    //     this.$refs.myQuillEditor.quill.insertEmbed(this.addRange !== null ? this.addRange.index : 0, this.uploadType, `${host}${fileObj.fileUrl}`, Quill.sources.USER)
    //     this.$refs.hiddenUpload.clearFiles()
    //   } catch (err) {
    //     console.log(err)
    //     this.$message.error(err.message || err.ResultSet.errors)
    //   }
    // },
    addMaterial (item) {
      this.selectIds = item.materialsList.map(row => row.materialId)
      this.currentItem = item
      this.showMaterialModal = true
    },
    delMaterial (item, row, rowIndex) {
      item.materialsList.splice(rowIndex, 1)
      let idIndex = this.selectIds.findIndex(id => id === row.materialId)
      this.selectIds.splice(idIndex, 1)
    },
    confirmModal (item) {
      let index = this.form.banner.findIndex(row => row.picId === item.picId)
      this.showMaterialModal = false
      this.currentItem = {}
      this.$nextTick(() => {
        this.$set(this.form.banner[index], 'materialsList', item.materialsList)
        this.$set(this.form.banner[index], 'moreNum', 3)
      })
    },
    closeModal () {
      this.showMaterialModal = false
      this.currentItem = {}
    },
    handleGridExceed () {
      this.$message.error('材料主图最多只能上传5张！')
    },
    async save () {
      try {
        if (!this.form.projectName) {
          this.$message.error('请输入案例名称！')
          return
        }
        if (!this.activeStyles.length) {
          this.$message.error('请选择所属业态！')
          return
        }
        // if (!this.form.styleId.length) {
        //   this.$message.error('请选择所属业态！')
        //   return
        // }
        if (!this.form.province && !this.form.city && !this.form.detailAddress) {
          this.$message.error('请选择并填写详细地址！')
          return
        }
        if (!this.form.caseDate) {
          this.$message.error('请选择项目时间！')
          return
        }
        if (!this.form.banner.length) {
          this.$message.error('请选择案例图片！')
          return
        }
        if (!this.form.projectDetail) {
          this.$message.error('请输入案例详情！')
          return
        }
        await this.$axios.post(addOrUpdate, { content: { ...this.form, styleId: this.activeStyles.join(',') } })
        this.$message.success('保存成功！')
        this.$router.back()
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async init () {
      try {
        const { ResultSet } = await this.$axios.post(getCaseDetail, { content: { materialCaseId: this.$route.params.id } })
        if (ResultSet.userData.Information.materialCaseInf.province) await this.getAddress({ type: 'citys', id: ResultSet.userData.Information.materialCaseInf.province })
        ResultSet.userData.picture.forEach(item => {
          item.moreNum = 3
        })
        this.form = { ...ResultSet.userData.Information.materialCaseInf, style: ResultSet.userData.Information.style, banner: ResultSet.userData.picture, province: parseInt(ResultSet.userData.Information.materialCaseInf.province), city: parseInt(ResultSet.userData.Information.materialCaseInf.city) }
        this.activeStyles = ResultSet.userData.Information.style.map(item => parseInt(item.styleId))
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  // mounted () {
  //   this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
  // },
  beforeRouteEnter (to, from, next) {
    next(async vm => {
      vm.getList()
      await vm.getAddress({ type: 'provinces' })
      await vm.getStyles()
      if (to.params.id) vm.init()
    })
  }
} 
</script>

<style lang="scss" scoped>
.edit {
  height: 100%;
}
.edit-warp {
  padding: 0 32px;
}
.edit-container {
  width: 100%;
  padding: 0 24px 40px;
  background: #FFFFFF;
  border-radius: 4px;
}
.edit-header {
  display: flex;
  align-items: center;
  padding: 16px 0;
}
.edit-header-title {
  margin-left: 16px;
  font-size: 16px;
  font-weight: bold;
  color: #363636;
}
.edit-section {
  margin-top: 24px;
}
.edit-section-title {
  font-size: 14px;
  font-weight: bold;
  color: #363636;
}
.edit-section-body {
  margin-top: 16px;
  padding: 32px 0;
  width: 100%;
  background: #F3F3F3;
}
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  &:last-child {
    margin-bottom: 0;
  }
  &.form-item-start {
    align-items: flex-start;
  }
}
.form-item-label {
  font-size: 14px;
  color: #363636;
  min-width: 120px;
  text-align: right;
  padding-right: 10px;
  line-height: 32px;
  &.important {
    &:before {
      content: '*';
      margin-right: 3px;
      color: #F56C6C;
    }
  }
}
.form-item-bd {
  .el-input, .el-select {
    width: 400px;
  }
  .el-textarea {
    width: 400px;
  }
}
.form-item-address {
  .el-select {
    width: 120px;
    margin-right: 20px;
    &:last-child {
      margin-right: 0;
    }
  }
}
.form-item-address-detail {
  margin-top: 16px;
}
.form-item-upload-info {
  font-size: 14px;
  color: #9E9E9E;
  margin-top: 8px;
}
.upload-photo {
  display: flex;
  align-items: flex-start;
  margin-top: 40px;
  .upload-img {
    width: 160px;
    height: 160px;
    border-radius: 4px;
    position: relative;
    .iconfont {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 99;
      transform: translate(50%, -50%);
    }
    .upload-img-bd {
      width: 100%;
      height: 128px;
      position: absolute;
      top: 0;
      left: 0;
      border-radius: 4px 4px 0 0;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
    }
  }
  .upload-materials {
    width: 400px;
    margin-left: 32px;
    background: #fff;
    border: 1px solid #CBCBCB;
    border-radius: 4px;
    .upload-tr-item:last-child {
      .upload-tr {
        border-bottom: none;
      }
    }
    .upload-tr {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #CBCBCB;
    }
    .upload-td {
      padding: 14px 16px;
      font-size: 14px;
      color: #363636;
      &.upload-td-bd {
        flex: 1;
        border-right: 1px solid #CBCBCB;
      }
      &.upload-handle {
        color: #FF2E42;
        width: 100px;
        cursor: pointer;
      }
    }
  }
}
.upload-img-add {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 32px;
  line-height: 32px;
  text-align: center;
  background: #FF2E42;
  border-radius: 0 0 4px 4px;
  cursor: pointer;
  color: #fff;
  font-size: 14px;
}
.edit-footer {
  margin-top: 16px;
  width: 100%;
  padding: 16px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}
.form-item-quill {
  min-height: 166px;
  & /deep/ .ql-container {
    min-height: 100px;
    background: #fff;
  }
}
.upload-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14px 16px;
  color: #576B95;
  background: #F3F3F3;
  cursor: pointer;
  .upload-more {
    font-size: 14px;
    margin-right: 5px;
  }
  .iconfont {
    font-size: 16px;
  }
}
</style>
